package com.web.security.util;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

public class MessageSourceUtils {

    private static MessageSource messageSource;

    public static String getMessage(String code, String[] arguments)
    {
        return getMessage(code, arguments, Locale.US);
    }
    
    public static String getMessage(String code, String[] arguments, Locale locale)
    {
        String [] lookedUpArguments = null;
        if (arguments != null && arguments.length > 0)
        {
            lookedUpArguments = new String[arguments.length];
            for (int i = 0; i < arguments.length; i++)
            {
                String argument = arguments[i];
                try
                {
                    String lookedUpArgument = messageSource.getMessage(argument, null, locale);
                    lookedUpArguments[i] = lookedUpArgument;
                }
                catch (NoSuchMessageException e)
                {
                    lookedUpArguments[i] = argument;
                }
            }
        }
        
        String message = null;
        try
        {
        	message = messageSource.getMessage(code, lookedUpArguments, locale);
        }
        catch (NoSuchMessageException e)
        {
        	message = code;
        }
        
        return message;
    }
    
    public static MessageSource getMessageSource()
    {
        return messageSource;
    }

    public static void setMessageSource(MessageSource messageSource)
    {
        MessageSourceUtils.messageSource = messageSource;
    }

}
